package com.hs.mod_archive.fragment

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.NavHostFragment
import com.hs.auth.LoginDialogFragment
import com.hs.common.dto.SysUserDto
import com.hs.framework.BuildConfig
import com.hs.framework.base.BaseDataBindFragment
import com.hs.framework.utils.DateUtils
import com.hs.framework.utils.getStringArrayFromResource
import com.hs.mod_archive.R
import com.hs.mod_archive.databinding.FragmentHomeBinding
import com.hs.mod_syslog.annotation.SysLogIntercept
import com.hs.room.model.archive.OptLog
import com.hs.room.repository.service.ILogRepository
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import java.util.Date
import javax.inject.Inject

/**
 * 主页：
 */
@AndroidEntryPoint
class FragmentHome : BaseDataBindFragment<FragmentHomeBinding>() {

    @Inject
    lateinit var service: ILogRepository
    private lateinit var handle: Handler
    private val ACTION_GET_NOW_TIME: Int = 1001
    val what = intArrayOf(
        R.id.goGet_,
        R.id.goStatusMonitor_,
        R.id.goArchiveManager_,
        R.id.goSysManager_,
        R.id.goFind_,
        R.id.goRevert_,
        R.id.goUserCenter_,
        R.id.goAlarm_,
        R.id.goApply_
    )

    init {
        handle = Handler(Looper.getMainLooper()) { msg ->
            when (msg.what) {
                ACTION_GET_NOW_TIME -> {
                    val date = Date()
                    mBinding!!.tvDate.text = DateUtils.formatDate(date)
                    mBinding!!.tvTimeBottomRight.text = DateUtils.formatDateHHMM(date)
                    mBinding!!.tvDateWeekday.text = DateUtils.getDayOfWeek(date)
                    handle.sendEmptyMessageDelayed(ACTION_GET_NOW_TIME, 1000)
                }
            }
            true
        }
    }


    private fun initBannerView() {
        val adapter = object : BannerImageAdapter<Int?>(
            listOf(
                R.mipmap.banner001,
                R.mipmap.banner002,
                R.mipmap.banner003,
                R.mipmap.banner004
            )
        ) {
            override fun onBindView(
                holder: BannerImageHolder?,
                data: Int?,
                position: Int,
                size: Int
            ) {
                holder?.imageView?.setImageResource(data!!)
            }
        }
        mBinding!!.banner.setAdapter(adapter)
        mBinding!!.banner.isAutoLoop(true)
        mBinding!!.banner.setIndicator(CircleIndicator(activity))
        mBinding!!.banner.scrollBarFadeDuration = 1000
        mBinding!!.banner.setIndicatorSelectedColor(Color.GREEN)
        mBinding!!.banner.start()
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        handle.sendEmptyMessageDelayed(ACTION_GET_NOW_TIME, 500)
        mBinding!!.tvVersion.text = BuildConfig.VERSION_NAME
        initBannerView()
        mBinding!!.goSysManager.setOnClickListener {
            LoginDialogFragment.show(requireActivity().supportFragmentManager,
                object : LoginDialogFragment.AuthListener {
                    override fun onAuthResult(sysUserDto: SysUserDto) {
                        sysUserDto.let {
                            // 有数据返回
                            println("账号密码登录 ：  ${sysUserDto.userName}")
                        } ?: run {
                            // 返回控
                        }
                    }
                })
        }
        mBinding!!.goGet.setOnClickListener {
            auth(what[0])
        }
        mBinding!!.goMonitor.setOnClickListener {
            auth(what[1])
        }
        mBinding!!.goFileManager.setOnClickListener {
            auth(what[2])
        }
        mBinding!!.goSysManager.setOnClickListener {
            auth(what[3])
        }
        mBinding!!.goFind.setOnClickListener {
            auth(what[4])
        }
        mBinding!!.goRevert.setOnClickListener {
            auth(what[5])
        }
        mBinding!!.goUserCenter.setOnClickListener {
            auth(what[6])
        }
        mBinding!!.goAlarm.setOnClickListener {
            auth(what[7])
        }
        mBinding!!.goApply.setOnClickListener {
            auth(what[8])
        }
    }

    @SysLogIntercept("go_")
    fun goThere(there: Int, u: SysUserDto) {
        NavHostFragment.findNavController(this@FragmentHome)
            .navigate(there, Bundle())
    }

    fun auth(where: Int) {
        LoginDialogFragment.show(requireActivity().supportFragmentManager,
            object : LoginDialogFragment.AuthListener {
                override fun onAuthResult(u: SysUserDto) {
                    // 有数据返回
                    println("账号密码登录 ：  ${u.userName}")
                    goThere(where, u)
                    val w = getStringArrayFromResource(R.array.what)
                    val date = DateUtils.getCurrentDate()
                    val str = DateUtils.formatDateHHMMSS(date)
                    val optLog = OptLog(
                        0,
                        0,
                        u.userName,
                        "${u.id}",
                        w[what.indexOf(where)],
                        str,
                        date.time,
                        u.screenshot,
                        u.loginType
                    )
                    lifecycleScope.launch {
                        service.insert(optLog)
                    }
                }
            }
        )


    }

    override fun onDestroyView() {
        super.onDestroyView()
        handle.removeCallbacksAndMessages(null)
        mBinding = null
    }

}